/*
 *
 * Project Name: tennis
 * $Id:  UserServiceImpl.java 2016-05-13 14:35:02 $
 */
package org.aceor.tennis.service.impl;

import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.aceor.tennis.common.domain.User;
import org.aceor.tennis.common.enums.ErrorCode;
import org.aceor.tennis.common.exception.BusinessRuntimeException;
import org.aceor.tennis.common.exception.CommonRuntimeException;
import org.aceor.tennis.dao.IBaseDAO;
import org.aceor.tennis.dao.IUserDAO;
import org.aceor.tennis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Slf4j
@Service("UserServiceImpl")
public class UserServiceImpl extends AbstractBaseService<IBaseDAO<User>, User> implements IUserService<User> {
    @Autowired
    private IUserDAO userDAO;

    public IBaseDAO<User> getDao() {
        return userDAO;
    }

    @Override
    public Optional<User> login(User user) throws BusinessRuntimeException {
        try {
            Map<String, Object> data = Maps.newHashMap();
            data.put("phone", user.getPhone());
            data.put("password", user.getPassword());
            return Optional.of(queryOne(data));
        } catch (Throwable e) {
            throw new BusinessRuntimeException(ErrorCode.LOGIN_ERROR, e);
        }
    }

    @Transactional
    @Override
    public Optional<User> register(User user) throws BusinessRuntimeException {
        try {
            User user0 = findOne("phone", user.getPhone());
            if (null != user0) {
                throw new BusinessRuntimeException(ErrorCode.USER_HAS_EXISTED);
            }
            if (1 == add(user)) {
                return Optional.of(user);
            }
        } catch (CommonRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new BusinessRuntimeException(ErrorCode.REGISTER_ERROR, e);
        }
        return Optional.absent();
    }
}
